#include <stdio.h>
#include <sys/socket.h>
#include <errno.h>
#include <netinet/ip.h>
#include <netinet/in.h>
#include <stdlib.h>

/*
* 该程序用于验证AF_INET原始套接字协议为0或者255的情况
* IPPROTO_IP / 0 : linux提示错误
* IPPROTO_RAW / 255 : 只能发送，不能接收
* 在netinet/in.h头文件中定义了各种IPPROTO_
* IPPROTO_IP = 0
* IPPROTO_ICMP = 1
* IPPROTO_IGMP = 2
* IPPROTO_TCP = 6
* IPPROTO_UDP = 17
* IPPROTO_RAW = 255
*/

#define BUFSIZE 2048
int main(int argc, char *argv[]) {

    int sockfd;
    int n, iphrlen, packetlen, protype, ipproto;
    char buf[BUFSIZ];
    if (argc < 2) {
        printf("error format\n");
        return -1;
    }
    ipproto = atoi(argv[1]);

    if( -1 == (sockfd = socket(AF_INET, SOCK_RAW, ipproto))) {
        perror("socket");
        return -1;
    }

    // 循环接收信息
    while(1) {
        n = recvfrom(sockfd, &buf, BUFSIZE, 0, 0, 0);
        if (n < 0) {
            perror("recvfrom");
            return -1;
        }
        struct ip *ip = (struct ip *)buf;
        // 计算长度
        iphrlen = ip->ip_hl << 2;
        packetlen = ntohs(ip->ip_len);
        protype = ip->ip_p;

        printf("iphrlen = %d, packetlen= %d, protype = %d\n", iphrlen, packetlen, protype);
    }

    return 0;
}